-- ============================================
-- ROCKET CASINO - MACHINE A SOUS
-- Le COMPUTER est le jeu (connexion + mise + rouleaux, tout au clavier).
-- Le MONITOR n'affiche QUE la Poke Ball Team Rocket qui tourne, en boucle,
-- purement decorative (jamais touchee, jamais utilisee pour jouer).
--
-- Fichier requis dans le meme dossier : client_solde.lua
-- ============================================

local bank = dofile("client_solde.lua")
math.randomseed(os.epoch and os.epoch("utc") or os.time())

-- ============================================
-- PARTIE 1 : POKE BALL DECORATIVE SUR LE MONITOR
-- ============================================

local function buildBannerLoop()
    local mon = peripheral.find("monitor")
    if not mon then
        return nil -- pas de moniteur branche : on continue sans deco
    end

    mon.setTextScale(0.5)
    mon.setBackgroundColor(colors.black)
    mon.clear()
    local W, H = mon.getSize()

    local FRAME_DELAY = 0.1
    local ROTATION_SPEED = 0.22

    local function newCanvas(bg)
        local c = {}
        for y = 1, H do
            c[y] = {}
            for x = 1, W do
                c[y][x] = { bg = bg, ch = " ", fg = colors.white }
            end
        end
        return c
    end

    local function px(canvas, x, y, bg, ch, fg)
        x, y = math.floor(x + 0.5), math.floor(y + 0.5)
        if x >= 1 and x <= W and y >= 1 and y <= H then
            local cell = canvas[y][x]
            if bg then cell.bg = bg end
            if ch then
                cell.ch = ch
                cell.fg = fg or cell.fg
            end
        end
    end

    local function render(canvas)
        local toBlit = colors.toBlit
        for y = 1, H do
            local row = canvas[y]
            local chars, fgs, bgs = {}, {}, {}
            for x = 1, W do
                local cell = row[x]
                chars[x] = cell.ch
                fgs[x] = toBlit(cell.fg)
                bgs[x] = toBlit(cell.bg)
            end
            mon.setCursorPos(1, y)
            mon.blit(table.concat(chars), table.concat(fgs), table.concat(bgs))
        end
    end

    local function fillEllipse(canvas, cx, cy, rx, ry, color)
        if rx <= 0 or ry <= 0 then return end
        for y = math.floor(cy - ry), math.ceil(cy + ry) do
            local dy = (y - cy) / ry
            local t = 1 - dy * dy
            if t >= 0 then
                local dx = rx * math.sqrt(t)
                for x = math.floor(cx - dx), math.ceil(cx + dx) do
                    px(canvas, x, y, color)
                end
            end
        end
    end

    local R_PATTERN = { "####.", "#...#", "#...#", "####.", "#..#.", "#...#", "#...#" }

    local function drawGlyphR(canvas, x0, y0, scale, color)
        for row = 1, #R_PATTERN do
            local line = R_PATTERN[row]
            for col = 1, #line do
                if line:sub(col, col) == "#" then
                    for sy = 0, scale - 1 do
                        for sx = 0, scale - 1 do
                            px(canvas, x0 + (col - 1) * scale + sx, y0 + (row - 1) * scale + sy, color)
                        end
                    end
                end
            end
        end
    end

    local function drawPokeball(canvas, cx, cy, r, angle)
        local squish = math.max(0.12, math.abs(math.cos(angle)))
        local rx = r * squish
        local ry = r

        fillEllipse(canvas, cx, cy, rx + 1.2, ry + 1.2, colors.gray)

        for y = math.floor(cy - ry), math.ceil(cy + ry) do
            local dy = (y - cy) / ry
            local t = 1 - dy * dy
            if t >= 0 then
                local dx = rx * math.sqrt(t)
                local color
                if y < cy - ry * 0.08 then
                    color = colors.black
                elseif y > cy + ry * 0.08 then
                    color = colors.red
                else
                    color = colors.lightGray
                end
                for x = math.floor(cx - dx), math.ceil(cx + dx) do
                    px(canvas, x, y, color)
                end
            end
        end

        for x = math.floor(cx - rx), math.ceil(cx + rx) do
            px(canvas, x, cy, colors.black)
        end

        local buttonR = math.max(1, r * 0.28 * squish)
        fillEllipse(canvas, cx, cy, buttonR + 0.6, buttonR + 0.6, colors.black)
        fillEllipse(canvas, cx, cy, buttonR, buttonR, colors.white)
        fillEllipse(canvas, cx, cy, buttonR * 0.5, buttonR * 0.5, colors.lightGray)

        if squish > 0.55 then
            local scale = math.max(1, math.floor(r * squish / 5))
            local rx0 = math.floor(cx - 2 * scale)
            local ry0 = math.floor(cy - ry * 0.75)
            for dx = -1, 1 do
                for dy = -1, 1 do
                    if dx ~= 0 or dy ~= 0 then
                        drawGlyphR(canvas, rx0 + dx, ry0 + dy, scale, colors.black)
                    end
                end
            end
            drawGlyphR(canvas, rx0, ry0, scale, colors.red)
        end
    end

    return function()
        local angle = 0
        local cx, cy = math.floor(W / 2), math.floor(H / 2)
        local r = math.floor(math.min(W, H) * 0.4)
        while true do
            local canvas = newCanvas(colors.black)
            drawPokeball(canvas, cx, cy, r, angle)
            render(canvas)
            angle = angle + ROTATION_SPEED
            sleep(FRAME_DELAY)
        end
    end
end

-- ============================================
-- PARTIE 2 : LE JEU, ENTIEREMENT SUR LE TERMINAL DU COMPUTER
-- ============================================

-- Symboles maison, thematique Team Rocket (rouge / noir / or)
local SYMBOLS = {
    { symbol = "@", color = colors.red,    value = 20, name = "Poke Ball Rocket" },
    { symbol = "7", color = colors.yellow, value = 10, name = "Sept dore" },
    { symbol = "*", color = colors.orange, value = 7,  name = "Etoile" },
    { symbol = "^", color = colors.red,    value = 5,  name = "Flamme" },
    { symbol = "$", color = colors.yellow, value = 3,  name = "Piece d'or" },
}

local MISE_MIN, MISE_MAX, MISE_STEP, MISE_DEFAULT = 1, 20, 1, 1
local bet = MISE_DEFAULT

local function centerText(y, text, textColor, bgColor)
    local w = select(1, term.getSize())
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.max(1, math.floor((w - #text) / 2) + 1)
    term.setCursorPos(x, y)
    term.write(text)
end

local function fillArea(x1, y1, x2, y2, bg)
    term.setBackgroundColor(bg)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", x2 - x1 + 1))
    end
end

local REEL_COUNT = 3
local SYM_W, SYM_H = 7, 3
local SEP_H = 1
local REEL_GAP = 2

local function randomSymbol()
    return math.random(1, #SYMBOLS)
end

local function drawSymbolBox(x1, y1, idx, isPayline)
    local sym = SYMBOLS[idx]
    local x2 = x1 + SYM_W - 1
    local y2 = y1 + SYM_H - 1
    term.setBackgroundColor(colors.black)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", SYM_W))
    end
    term.setTextColor(sym.color)
    local midY = y1 + math.floor(SYM_H / 2)
    local midX = x1 + math.floor((SYM_W - 1) / 2)
    term.setCursorPos(midX, midY)
    term.write(sym.symbol)

    if isPayline then
        term.setTextColor(colors.red)
        term.setCursorPos(x1, midY)
        term.write(">")
        term.setCursorPos(x2, midY)
        term.write("<")
    end
end

local function drawSeparator(x1, y, isPayline)
    term.setBackgroundColor(colors.black)
    term.setTextColor(isPayline and colors.red or colors.gray)
    term.setCursorPos(x1, y)
    term.write(string.rep("-", SYM_W))
end

local function makeGeometry()
    local w, h = term.getSize()
    local totalReelWidth = REEL_COUNT * SYM_W + (REEL_COUNT - 1) * REEL_GAP
    local reelsLeft = math.max(1, math.floor((w - totalReelWidth) / 2) + 1)
    local reelsTop = 8

    local geo = { w = w, h = h, left = reelsLeft, top = reelsTop }
    geo.rowTopY = reelsTop
    geo.sep1Y = geo.rowTopY + SYM_H
    geo.rowMidY = geo.sep1Y + SEP_H
    geo.sep2Y = geo.rowMidY + SYM_H
    geo.rowBotY = geo.sep2Y + SEP_H
    geo.reelBottom = geo.rowBotY + SYM_H - 1

    function geo.reelX(i)
        return reelsLeft + (i - 1) * (SYM_W + REEL_GAP)
    end

    return geo
end

local function drawReel(geo, i, reel)
    local x = geo.reelX(i)
    drawSymbolBox(x, geo.rowTopY, reel.top, false)
    drawSeparator(x, geo.sep1Y, true)
    drawSymbolBox(x, geo.rowMidY, reel.mid, true)
    drawSeparator(x, geo.sep2Y, true)
    drawSymbolBox(x, geo.rowBotY, reel.bot, false)
end

local function drawAllReels(geo, reels)
    for i, reel in ipairs(reels) do
        drawReel(geo, i, reel)
    end
end

local function drawHeader(player, points)
    fillArea(1, 1, select(1, term.getSize()), 3, colors.black)
    centerText(1, "== ROCKET CASINO - MACHINE A SOUS ==", colors.red)
    centerText(2, "Agent : " .. player, colors.yellow)
    centerText(3, "Points : " .. points .. "    Mise : " .. bet, colors.orange)
end

local function drawMessage(geo, text, textColor)
    fillArea(1, 6, geo.w, 6, colors.black)
    if text then
        centerText(6, text, textColor or colors.lightGray)
    end
end

local function drawFooter(geo, text, textColor)
    fillArea(1, geo.reelBottom + 1, geo.w, geo.h, colors.black)
    if text then
        centerText(geo.reelBottom + 2, text, textColor or colors.lightGray)
    end
end

local function drawMenu(geo)
    local line = "[+] mise  [-] mise  [ENTREE] tourner  [q] quitter"
    fillArea(1, 5, geo.w, 5, colors.black)
    centerText(5, line, colors.orange)
end

local function dollarRain(geo, ticks)
    local drops = {}
    for i = 1, 12 do
        drops[i] = { x = math.random(1, geo.w), y = math.random(-10, 0) }
    end

    for t = 1, ticks do
        for _, d in ipairs(drops) do
            term.setBackgroundColor(colors.black)
            term.setCursorPos(d.x, d.y)
            term.write(" ")
            d.y = d.y + 1
            if d.y > geo.h then
                d.x = math.random(1, geo.w)
                d.y = math.random(-6, 0)
            elseif d.y >= 1 then
                term.setTextColor(colors.yellow)
                term.setCursorPos(d.x, d.y)
                term.write("$")
            end
        end
        sleep(0.06)
    end

    for _, d in ipairs(drops) do
        term.setBackgroundColor(colors.black)
        term.setCursorPos(d.x, math.min(d.y, geo.h))
        term.write(" ")
    end
end

local function evaluateWin(i1, i2, i3, currentBet)
    if i1 == i2 and i2 == i3 then
        return SYMBOLS[i1].value * currentBet, "JACKPOT ! 3x " .. SYMBOLS[i1].name
    elseif i1 == i2 or i2 == i3 or i1 == i3 then
        local matchIdx = (i1 == i2) and i1 or ((i2 == i3) and i2 or i1)
        return math.floor(SYMBOLS[matchIdx].value / 2) * currentBet, "Petit gain ! 2x " .. SYMBOLS[matchIdx].name
    else
        return 0, nil
    end
end

local function playRound(player, points)
    local geo = makeGeometry()

    if points < bet then
        drawMessage(geo, "PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return points
    end

    local newBal1, err1 = bank.addBalance(player, -bet)
    if not newBal1 then
        drawMessage(geo, err1 or "Erreur banque, reessaie.", colors.red)
        sleep(2)
        return points
    end
    points = newBal1

    local reels = {}
    for i = 1, REEL_COUNT do
        reels[i] = { top = randomSymbol(), mid = randomSymbol(), bot = randomSymbol() }
    end

    local stopTicks = { 14, 20, 26 }
    local maxTick = stopTicks[REEL_COUNT]

    drawHeader(player, points)
    drawFooter(geo, "Les rouleaux tournent...", colors.white)

    for tick = 1, maxTick do
        for i, reel in ipairs(reels) do
            if tick <= stopTicks[i] then
                reel.top = reel.mid
                reel.mid = reel.bot
                reel.bot = randomSymbol()
            end
        end
        drawAllReels(geo, reels)
        sleep(0.04 + tick * 0.004)
    end

    local i1, i2, i3 = reels[1].mid, reels[2].mid, reels[3].mid
    local gain, message = evaluateWin(i1, i2, i3, bet)

    if gain > 0 then
        local newBal2 = bank.addBalance(player, gain)
        points = newBal2 or points
    end

    drawHeader(player, points)

    if gain > 0 then
        drawFooter(geo, message .. " (+" .. gain .. ")", colors.yellow)
        dollarRain(geo, 20)
        drawAllReels(geo, reels)
        drawHeader(player, points)
        drawFooter(geo, message .. " (+" .. gain .. ")", colors.yellow)
    else
        drawFooter(geo, "Perdu... reessaie !", colors.red)
    end

    sleep(1.5)
    return points
end

local function authenticateKeyboard()
    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(2, "=== ROCKET CASINO ===", colors.red)
    term.setCursorPos(1, 4)
    term.setTextColor(colors.white)
    term.write("Pseudo Minecraft : ")
    local username = read()

    while true do
        term.setTextColor(colors.white)
        term.write("Mot de passe : ")
        local password = read("*")
        local ok, err = bank.authenticate(username, password)
        if ok then
            return username
        else
            term.setTextColor(colors.red)
            print(err or "Erreur de connexion, reessaie.")
        end
    end
end

local function runSession()
    local player = authenticateKeyboard()
    local points = bank.getBalance(player)
    bet = MISE_DEFAULT

    local idleReels = {
        { top = 1, mid = 1, bot = 1 },
        { top = 2, mid = 2, bot = 2 },
        { top = 3, mid = 3, bot = 3 },
    }

    local playing = true
    while playing do
        local geo = makeGeometry()
        drawHeader(player, points)
        drawMenu(geo)
        drawMessage(geo, nil)
        drawAllReels(geo, idleReels)
        drawFooter(geo, "Mise min " .. MISE_MIN .. " - max " .. MISE_MAX, colors.gray)

        term.setCursorPos(1, geo.h)
        term.setBackgroundColor(colors.black)
        term.setTextColor(colors.white)
        term.write("> ")
        local cmd = read()

        if cmd == "+" then
            bet = math.min(MISE_MAX, bet + MISE_STEP)
        elseif cmd == "-" then
            bet = math.max(MISE_MIN, bet - MISE_STEP)
        elseif cmd == "q" or cmd == "Q" then
            playing = false
        else
            points = playRound(player, points)
        end
    end
end

local function gameLoop()
    while true do
        runSession()
    end
end

-- ============================================
-- LANCEMENT : Poke Ball deco sur le moniteur + jeu sur le computer
-- ============================================

local bannerLoop = buildBannerLoop()

if bannerLoop then
    parallel.waitForAll(bannerLoop, gameLoop)
else
    gameLoop()
end